﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;

namespace Common
{
    public class FDLMiddleware
    {
        private string[] picSuffix = new string[] { ".jpg", ".gif", ".png" };
        private readonly RequestDelegate _next;
        private readonly string _wwwrootFolder;

        public FDLMiddleware(RequestDelegate next, IWebHostEnvironment env)
        {
            _wwwrootFolder = env.WebRootPath;
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            var url = context.Request.Path.Value;
            var host = $"{context.Request.Scheme}://{context.Request.Host.Value}";
            var urlReferrer = context.Request.Headers["Referer"].FirstOrDefault<string>();
            if (picSuffix.Any(x => url.Contains(x))
                && !string.IsNullOrEmpty(urlReferrer)
                && !urlReferrer.StartsWith(host))
            {
                var unauthorizedImagePath = Path.Combine(_wwwrootFolder, "img/Unauthorized.png");
                await context.Response.SendFileAsync(unauthorizedImagePath);
            }
            else
            {
                await _next(context);
            }
        }
    }
    public static class BuilderExtensions
    {
        /// <summary>
        /// 扩展方法防盗链
        /// 请放在静态文件中间件之前
        /// app.UseFDL();
        /// app.UseStaticFiles();
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseFDL(this IApplicationBuilder app)
        {
            return app.UseMiddleware<FDLMiddleware>();
        }
    }
}
